const express = require('express')
const router = express.Router()
const Class = require('../../models/class')

//添加文章分类
//@POST /api/class/addClass
router.post('/addClass', (req, res) => {
  console.log(req.body)
  Class.findOne({ class_name: req.body.class_name })
    .then(doc => {
      console.log(doc)
      if (doc) {
        return res.send({ message: "分类已经创建", state: 0 })
      } else {
        Class.create(req.body)
          .then((doc) => res.send({
            state: 1,
            message: "创建成功",
            doc: doc,
          }))
          .catch(err => res.status(400).json(err.message))
      }
    })
    .catch(error => res.status(400).json(err.message))
})

//修改分类信息
//@POST /api/class/update
router.post('/update/:id', (req, res) => {
  Class.findByIdAndUpdate(req.params.id, { class_name: req.body.class_name, detail: req.body.detail })
    .then(doc => res.send({
      doc: doc,
      msg: '修改成功',
      state: 1
    }
    ))
    .catch(err => res.status(400).json(err.message))
})

//删除分类
//@DELETE /api/class/deleteClass
router.delete('/deleteClass/:id', (req, res) => {
  Class.findByIdAndDelete(req.params.id)
    .then(doc => res.send({
      state:1,
      message:'删除分类成功',
      doc:doc
    }))
    .catch(err => res.status(400).json(err.message))
})
//获取分类列表
//@GET /api/class/getAll
router.get('/getAll', (req, res) => {
  Class.find({})
    .then(doc => res.send({
      state:1,
      message:'获取分类成功',
      doc:doc
    }))
    .catch(err => res.status(400).json(err.message))
})

//更新分类数
//@GET /api/class/blogNum
router.post('/blogNum', (req, res) => {
  console.log(req.body)
  for (let i in req.body) {
    Class.findOneAndUpdate({ class_name: i }, { $set: { blog_num: req.body[i] } })
      .then(doc => console.log(doc))
  }
  res.send({
    state: 1,
    message: '更新分类数成功'
  })
})

module.exports = router